<?php
declare (strict_types = 1);

namespace app\controller\v1;

use think\Request;
use think\Response;
use think\exception\ValidateException;
use app\service\UserService;
use app\model\User;

/**
 * 用户登录控制器
 * 处理用户登录、注册等认证相关功能
 */
class UserLoginController extends BaseAPIController
{
    public function login(Request $request)
    {
         try {
            // 获取请求参数（中间件已处理加密解密）
            $params = $request->param();
            // 调用用户服务进行登录
            $result = $this->userService->login($params);
            return $this->success($result, '登录成功');
        } catch (ValidateException $e) {
            return $this->error($e->getMessage(), 400);
        } catch (\Exception $e) {
            trace('登录失败: ' . $e->getMessage(), 'error');
            return $this->error('登录失败，请重试'.$e->getMessage(), 500);
        }
    }

    
   
    
    /**
     * 刷新Token
     *
     * @param Request $request
     * @return Response
     */
    public function refreshToken(Request $request)
    {
        try {
            $token = $request->header('Authorization');
            if (!$token || !preg_match('/Bearer\s+(\S+)/', $token, $matches)) {
                return $this->error('缺少认证信息', 401);
            }
            
            $newToken = $this->userService->refreshToken($matches[1]);
            if (!$newToken) {
                return $this->error('Token刷新失败', 401);
            }
            
            return $this->success(['token' => $newToken], 'Token刷新成功');
            
        } catch (\Exception $e) {
            trace('Token刷新失败: ' . $e->getMessage(), 'error');
            return $this->error('Token刷新失败', 500);
        }
    }

    
    /**
     * 获取当前用户信息
     *
     * @return Response
     */
    public function info()
    {
        try {
            $user = UserService::getCurrentUser();
            if (!$user) {
                return $this->error('用户未登录', 401);
            }
            
            return $this->success($user, '获取成功');
        } catch (\Exception $e) {
            return $this->error('获取用户信息失败', 500);
        }
    }
    
    /**
     * 修改密码
     *
     * @param Request $request
     * @return Response
     */
    public function changePassword(Request $request)
    {
        try {
            $userId = UserService::getCurrentUserId();
            if (!$userId) {
                return $this->error('用户未登录', 401);
            }
            
            $params = $request->param();
            if (empty($params['old_password']) || empty($params['new_password'])) {
                return $this->error('原密码和新密码不能为空', 400);
            }
            
            $result = $this->userService->changePassword(
                $userId,
                $params['old_password'],
                $params['new_password']
            );
            
            if ($result) {
                return $this->success([], '密码修改成功');
            } else {
                return $this->error('密码修改失败', 500);
            }
            
        } catch (ValidateException $e) {
            return $this->error($e->getMessage(), 400);
        } catch (\Exception $e) {
            trace('修改密码失败: ' . $e->getMessage(), 'error');
            return $this->error('密码修改失败', 500);
        }
    }

    // 上传头像
    public function uploadAvatar(Request $request)
    {
        try {
            
            
            $file = $request->file('file');
            if (!$file) {
                return $this->error('请上传头像', 400);
            }
            
            $result = $this->userService->uploadAvatar(mt_rand(100000, 999999), $file);
            if ($result) {
                return $this->success($result, '头像上传成功');
            } else {
                return $this->error('头像上传失败', 500);
            }
            
        } catch (\Exception $e) {
            trace('上传头像失败: ' . $e->getMessage(), 'error');
            return $this->error('头像上传失败', 500);
        }
    }
   
}
